package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.service.VideoApi;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author げっしょく
 * @date 2021/11/1
 */
@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public String save(Video video) {
        Long vid = idWorker.getNextId("video");
        video.setVid(vid);
        video.setCreated(System.currentTimeMillis());
        mongoTemplate.save(video);
        return video.getId().toHexString();
    }

    //根据vid进行查找
    @Override
    public List<Video> getVideo(List<Integer> collect) {
        //设置查询条件
        Query q = Query.query(Criteria.where("vid").in(collect));
        //查找出数据返回
        return mongoTemplate.find(q, Video.class);
    }

    //大数据推荐少了,补充
    @Override
    public List<Video> getSupplement(Integer foller) {
        Query with = Query.query(new Criteria()).limit(foller).with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(with, Video.class);
    }

    //从数据库中查找最新发布的视频推荐给用户
    @Override
    public List<Video> getPageVideo(Integer page, Integer pagesize, Integer foller) {
        Query query = Query.query(new Criteria()).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Video.class);
    }

    @Override
    public PageResult getByIdVideos(Long userId, Integer page, Integer pagesize) {
        Query q = Query.query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(q, Video.class);
        q.skip((page - 1) * pagesize).limit(pagesize);
        List<Video> videos = mongoTemplate.find(q, Video.class);
        return new PageResult(page, pagesize, count, videos);
    }
}
